package com.hyfrogx.modules.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.param.VodConvertParam;
import com.hyfrogx.common.param.VodStatus;
import com.hyfrogx.common.qcloud.QcloudApiModuleCenter;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.form.video.VodVideoVo;
import com.hyfrogx.modules.app.utils.VodSignUtils;
import com.hyfrogx.modules.app.utils.VodUtils;
import com.hyfrogx.modules.manage.dao.HyVideoVodDao;
import com.hyfrogx.modules.manage.entity.video.HyVideoVodEntity;
import com.hyfrogx.modules.manage.entity.video.VideoVodInfoEntity;
import com.hyfrogx.modules.manage.form.video.ConvertVodFileForm;
import com.hyfrogx.modules.manage.service.HyVideoVodService;
import com.hyfrogx.modules.manage.service.HyVideoVodInfoService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName LvbVideoServiceImpl
 * @Description TODO
 * @Author yangjun
 * @date 2019/12/4 16:11
 * @Version 1.0
 **/
@Service
public class HyVideoVodServiceImpl extends ServiceImpl<HyVideoVodDao, HyVideoVodEntity> implements HyVideoVodService {

    @Autowired
    HyVideoVodInfoService hyVideoVodInfoService;

    // 上传完成log
    Logger fileUploadLog = LoggerFactory.getLogger("NewFileUpload");

    // 转码完成log
    Logger covertLog = LoggerFactory.getLogger("ProcedureStateChanged");


    @Override
    public int isExistVideoBychannelId(String channelId) {
        return this.baseMapper.selectCount(new QueryWrapper<HyVideoVodEntity>().eq("channel_id",channelId));
    }

    @Override
    public IPage getVideoVodByConditions(QueryExt queryExt) {
        Map map=new HashMap();
        map.putAll(queryExt.getCondition());
        queryExt.setRecords(this.baseMapper.getVideoVodByConditions(queryExt,map));
        return queryExt;
    }

    @Override
    public Object getFileByFileId(String vodId) throws Exception{
        QcloudApiModuleCenter module = VodUtils.getConfig();
        TreeMap<String, Object> params = VodUtils.getParam();
        params.put("fileIds.1", vodId);// 传入list,开始for循环,参数格式为: fileIds.n n为集合长度下标
        String result = module.call("DescribeVodInfo", params);//批量获取
        JSONObject object = new JSONObject(result);
        return object.toString();
    }

    @Override
    public IPage findVideoVodListByTypeAndChannel(QueryExt queryExt) {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        queryExt.setRecords(this.baseMapper.findVideoVodListByTypeAndChannel(queryExt, map));
        return queryExt;
    }

    @Override
    public VodVideoVo getVodVideoByVid(Integer id) throws ServiceException {

        VodVideoVo video = this.baseMapper.getVodVideoByVid(id);
		if (video == null) {
			return video;
		}
		// 如果发现该资源收费,不给与客户端播放地址
		if(video.getPrice().doubleValue()>0.00){
			return video;
		}
		List<VideoVodInfoEntity> infos = hyVideoVodInfoService.getBaseMapper().selectList(new QueryWrapper<VideoVodInfoEntity>().eq("vod_id",video.getId()));
		video.setVodInfos(infos);
        return video;
    }

    @Override
    public void ConvertVodFile(ConvertVodFileForm form)  throws Exception  {
        HyVideoVodEntity vod=this.baseMapper.selectOne(new QueryWrapper<HyVideoVodEntity>().eq("file_id",form.getFileId()));
        if (vod == null) {
            throw new ServiceException("文件不存在,转码失败");
        }
        if (vod.getStatus().intValue() != VodStatus.WAIT_CONVERT.getCode()) {
            throw new ServiceException("状态异常");
        }

        //腾讯云
        QcloudApiModuleCenter module = VodUtils.getConfig();
        TreeMap<String, Object> params = VodUtils.getParam();
        params.put("fileId", form.getFileId());

        // 处理转码参数
        Map<String, Object> transcode = new HashMap<>();
        Integer[] trans_definitions = {};
        int type=form.getType().intValue();
        if (type == 0) {
            trans_definitions = VodConvertParam.T1.trans_definitions;
        } else if (type == 1) {
            trans_definitions = VodConvertParam.T2.trans_definitions;
        } else if (type== 2) {
            trans_definitions = VodConvertParam.T3.trans_definitions;
        } else if (type == 3) {
            trans_definitions = VodConvertParam.T4.trans_definitions;
        } else {
            trans_definitions = VodConvertParam.T5.trans_definitions;
        }
        // 对视频进行转码，转码输出模板为10，20，30，40，
        for (int i = 0; i < trans_definitions.length; i++) {
            params.put("transcode.definition." + i, trans_definitions[i]);
        }
        // 要求禁止将低码率视频转为高码率视频；
        transcode.put("transcode.disableHigherBitrate", 1);
        params.put("notifyMode", "Finish");
        String result = null;
        result = module.call("ProcessFile", params);

        JSONObject object = new JSONObject(result);
        if (object.getInt("code") == 0) {
            String vodTaskId = object.getString("vodTaskId");
            vod.setVodTaskId(vodTaskId);
        } else {
            throw new ServiceException(object.toString());
        }
        //更新数据
        vod.setStatus(VodStatus.CONVERTING.getCode());
        vod.setUpdateDate(new Date());
        this.baseMapper.updateById(vod);
    }


    @Override
    public String getSign(Map map) throws ServiceException {
        String sign = VodSignUtils.getSign(map);
        return sign;
    }

    @Override
    public void callBack(String data) throws Exception {
        JSONObject json = new JSONObject(data);
        // 获取当前事件类型
        String eventType = json.getString("eventType");
        // 如果事件类型是上传完成
        if ("NewFileUpload".equals(eventType)) {
            fileUploadLog.info("当前时间：" + new Date() + "--------接收到腾讯云回调上传完成:" + json);
            // 获取详细信息体
            JSONObject jdata = json.getJSONObject("data");
        } else if ("ProcedureStateChanged".equals(eventType)) {
            // 如果APP配置了事件通知，则在任务流状态变更之后，点播后台会将该事件通知给APP后台。
            JSONObject jsondata = json.getJSONObject("data");
            String fileId = jsondata.getString("fileId");
            String status = jsondata.getString("status");
            Integer duration = jsondata.getJSONObject("metaData").getInt("duration");//时长
            // 如果事件完成
            if (status.equals("FINISH")) {
                HyVideoVodEntity vod=this.baseMapper.selectOne(new QueryWrapper<HyVideoVodEntity>().eq("file_id",fileId));
                if (vod == null) {
                    log.error(fileId+"视频文件不存在");
                    return;
                }
                vod.setStatus(VodStatus.WAIT_EDIT.getCode());
                vod.setTime(duration.toString());
                vod.setUpdateDate(new Date());
                this.baseMapper.updateById(vod);
                Integer vodId=vod.getId();

                //获取转码后的视频文件数据
                List<VideoVodInfoEntity> list=hyVideoVodInfoService.getConvertVideoInfoListFromQcloud(fileId);
                if(list!=null&&list.size()>0){
                    for(VideoVodInfoEntity info:list){
                        info.setVodId(vodId);
                        hyVideoVodInfoService.getBaseMapper().insert(info);
                    }
                }
                covertLog.info("当前channel_id为：" + "--------:" + fileId);
                covertLog.info("当前时间：" + new Date() + "--------接收到腾讯云回调转码完成:" + jsondata);
            } else {
                log.error(jsondata.toString());
            }
        }
    }
}
